package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void save(Employee entity, Long[] ids) {//ids:多个角色id
        employeeMapper.insert(entity);//添加一个对象
        //维护与角色关系
        if(ids != null){
            for (Long id : ids) {
                employeeMapper.insertRelation(entity.getId(), id);//往关系表中添加多个角色id
            }
        }
    }

    @Override
    public void update(Employee entity, Long[] ids) {

        //删除关系
        employeeMapper.deleteRelation(entity.getId());
        employeeMapper.updateByPrimaryKey(entity);

        //维护与角色关系
        if(ids != null){
            for (Long id : ids) {
                employeeMapper.insertRelation(entity.getId(), id);
            }
        }
    }

    @Override
    public void delete(Long id) {
        //删除关系
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> list() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {

        int totalCount =  employeeMapper.selectForCount(qo);

        if(totalCount == 0){
            return PageResult.EMPTY_PAGE_RESULT;
        }

        List<Employee> list = employeeMapper.selectForList(qo);
        return new PageResult(list, totalCount, qo.getCurrentPage(), qo.getPageSize());
    }


}
